//
//  GoodsQrCodeViewController.m
//  KingSelected
//
//  Created by 杨鹏 on 2023/11/7.
//

#import "GoodsQrCodeViewController.h"
#import "YPLabel.h"

@interface GoodsQrCodeViewController ()

@property (nonatomic, copy) NSString *codeUrl;
@property (nonatomic, strong) UIImageView *qrImageV;
@property (nonatomic, strong) UIView *contentView;
@end

@implementation GoodsQrCodeViewController

- (void)initDidLoad {
    self.navigationTitle = @"商品二维码";
}

- (void)initViews {
    self.view.backgroundColor = [UIColor gradientFromColor:kRGB(0xFFC19A) toColor:kRGB(0xFF9754) withHeight:kHeightForScreen];
    
    self.contentView = [[UIView alloc] init];
    self.contentView.backgroundColor = [UIColor whiteColor];
    self.contentView.layer.cornerRadius = 8;
    self.contentView.layer.masksToBounds = YES;
    [self.view addSubview:self.contentView];
    
    UIView *topView = [[UIView alloc] init];
    topView.backgroundColor = kRGB(0xFFEADD);
    topView.layer.cornerRadius = 8;
    topView.layer.masksToBounds = YES;
    [self.contentView addSubview:topView];
    
    NSString *str = @"1. 尽量用APP扫一扫\n2. 微信如果扫不开用浏览器扫一扫\n3. 如果ma封了，在个人中心更新ma即可\n4. 永久网址是：https://www.xuanpingwang.com";
    NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithString:str];
    NSRange range = [str rangeOfString:@"APP扫一扫"];
    NSRange range1 = [str rangeOfString:@"https://www.xuanpingwang.com"];
    [attr addAttributes:@{NSForegroundColorAttributeName:kBgColor} range:range];
    [attr addAttributes:@{NSForegroundColorAttributeName:kBgColor} range:range1];
    NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc] init];
    paragraph.lineSpacing = 6;
    [attr addAttributes:@{NSParagraphStyleAttributeName:paragraph} range:NSMakeRange(0, str.length)];
    
    YPLabel *label = [[YPLabel alloc] init];
    label.textColor = kRGB(0x666666);
    label.font = kFontMediium(12);
    label.numberOfLines = 0;
    [label setVerAlignment:VerticalAlgnment_center];
    label.attributedText = attr;
    [topView addSubview:label];
    
    UILabel *tiplabel = [[UILabel alloc] init];
    tiplabel.text = @"如遇微信二维码扫不开，重新生成即可恢复访问";
    tiplabel.textColor = kBgColor;
    tiplabel.font = kFontRegula(11);
    [tiplabel sizeToFit];
    [self.contentView addSubview:tiplabel];
    
    UIImageView *qrbg = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"goodsqrBg"]];
    [self.contentView addSubview:qrbg];
    
    [qrbg addSubview:self.qrImageV];
    
    UIButton *refreshBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [refreshBtn setImage:[UIImage imageNamed:@"icon_refresh"] forState:UIControlStateNormal];
    [refreshBtn setTitle:@"刷新二维码" forState:UIControlStateNormal];
    [refreshBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    refreshBtn.titleLabel.font = kFontMediium(12);
    refreshBtn.layer.cornerRadius = 14;
    refreshBtn.layer.borderColor = [UIColor whiteColor].CGColor;
    refreshBtn.layer.borderWidth = 1;
    refreshBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 5);
    [self.view addSubview:refreshBtn];
    @weakify(self)
    [[refreshBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        @strongify(self)
        [self initRequestData];
    }];
    
    UIButton *saveBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [saveBtn setTitle:@"保存二维码" forState:UIControlStateNormal];
    [saveBtn setTitleColor:kBgColor forState:UIControlStateNormal];
    saveBtn.titleLabel.font = kFontMediium(16);
    saveBtn.layer.cornerRadius = 20;
    saveBtn.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:saveBtn];
    [[saveBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        @strongify(self)
        [self saveImageWithView];
    }];
    
    [self.contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(0);
        make.top.mas_equalTo(20);
        make.size.mas_equalTo(CGSizeMake((kWidthForScreen-32), 470));
    }];
    [topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(25);
        make.trailing.mas_equalTo(-25);
        make.top.mas_equalTo(25);
        make.height.mas_equalTo(105);
    }];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsMake(8, 10, 8, 10));
    }];
    [tiplabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(0);
        make.top.mas_equalTo(topView.mas_bottom).offset(30);
    }];
    [qrbg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(0);
        make.bottom.mas_equalTo(-30);
        make.width.height.mas_equalTo(250);
    }];
    [self.qrImageV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsMake(20, 20, 20, 20));
    }];
    [refreshBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(0);
        make.top.mas_equalTo(self.contentView.mas_bottom).offset(30);
        make.size.mas_equalTo(CGSizeMake(100, 28));
    }];
    [saveBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(0);
        make.top.mas_equalTo(refreshBtn.mas_bottom).offset(40);
        make.size.mas_equalTo(CGSizeMake(230, 40));
    }];
}

- (void)initRequestData {
    [YPProgressHud showHudInview:self.view];
    [NET getGoodsQrCode:self.goodsId success:^(id  _Nonnull responseObject) {
        self.codeUrl = responseObject[@"codeUrl"];
        [self.qrImageV sd_setImageWithURL:[NSURL URLWithString:self.codeUrl]];
        [YPProgressHud hideHudForView:self.view];
    } failure:^(NSError * _Nonnull error) {
        kShowText(error.userInfo[kHttpErrorReason]);
        [YPProgressHud hideHudForView:self.view];
    }];
}

- (void)saveImageWithView {
    [YPProgressHud showHudInview:self.view];
    UIGraphicsBeginImageContextWithOptions(self.contentView.frame.size,NO,0.0);
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    [self.contentView.layer renderInContext:ctx];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    UIImageWriteToSavedPhotosAlbum(image, self, @selector(saveImage:finishSaveWithError:context:), nil);
}

- (void)saveImage:(UIImage *)img finishSaveWithError:(NSError *)error context:(void*)context {
    if (error) {
        kShowText(@"保存失败,请稍后再试");
    }else {
        kShowText(@"保存成功");
    }
    [YPProgressHud hideHudForView:self.view];
}

- (UIImageView *)qrImageV {
    if (!_qrImageV) {
        _qrImageV = [[UIImageView alloc] init];
        _qrImageV.contentMode = UIViewContentModeScaleAspectFit;
    }
    return _qrImageV;
}


@end
